/*
 * @Author: your name
 * @Date: 2021-09-15 09:34:48
 * @LastEditTime: 2021-09-16 13:45:08
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \media_system\routes\index.js
 */
const { Sequelize, DataTypes } = require("sequelize");
const moment = require('moment');
const { User, Bloodglucose, Food } = require('../database/index')
const Router = require('@koa/router')
const { formatResponse,filterColumn } = require("../utils/common");
const router = new Router()

/**
 * @swagger
 *  /bloodglucose/add: #接口访问路径(拼接上之前swagger.js中的host)
 *    post: #请求方式
 *     summary: 添加当前用户血糖记录  #接口信息
 *     description: 添加当前用户血糖记录 #接口描述
 *     tags: [血糖记录] #接口分组
 *     produces:
 *       - application/json
 *     requestBody:
 *         content:
 *            application/x-www-form-urlencoded:
 *               schema:
 *                  type: object
 *                  required:
 *                  - bloodglucoseValue
 *                  - dietStatus
 *                  - recordTime
 *                  - userId
 *                  properties:
 *                    userId:
 *                      type: string
 *                      description: 用户ID
 *                    bloodglucoseValue:
 *                      type: number
 *                      description: 血糖值
 *                    recordTime:
 *                      type: string
 *                      description: 记录时间,格式为2023-09-22 16:41:23
 *                      pattern: "yyyy-MM-dd HH:mm:ss"
 *                      example: "2023-09-22 16:41:23"
 *                    dietStatus:
 *                      type: integer
 *                      enum: [ "0", "1", "2", "3","4", "5", "6", "7","8"]
 *                      description: 血糖监测状态（0 早餐前 1 早餐后 2午餐前 3午餐后 4晚餐前 5晚餐后 6睡前 7凌晨 8随机） 
 *     responses: #返回结果
 *       200:
 *         description: 成功
 */
router.post("/add", async function (ctx, next) {
  let bloodglucose = ctx.request.body;
  // console.log("bloodglucose:", bloodglucose);
  const cBloodglucose = await Bloodglucose.create({
    bloodglucoseValue: bloodglucose.bloodglucoseValue,
    dietStatus: bloodglucose.dietStatus,
    recordTime: bloodglucose.recordTime,
  });
  const cuser = User.build({
    userId:bloodglucose.userId
  })
  await cBloodglucose.setUser(cuser)

  if (cBloodglucose) {
    ctx.body = formatResponse("200", { ...cBloodglucose.get({ plain: true }) }, "success");
  } else {
    ctx.body = formatResponse("500", "", "fail");
  }
});


/**
 * @swagger
 * /bloodglucose/getBloodglucoseByDates:
 *   get:
 *     security:
 *       - bearerAuth: []
 *     summary: 查询当前用户指定时间段的血糖信息
 *     description: 查询当前用户指定时间段的血糖信息
 *     tags: [血糖记录]
 *     parameters:
 *       - name: userId
 *         in: query #参数存放位置。query是存放到请求头里边
 *         required: true
 *         description: 用户id
 *         type: string
 *       - name: startDate
 *         in: query #参数存放位置。query是存放到请求头里边
 *         required: true
 *         description: 起始日期,例如2017-07-21
 *         type: string
 *       - name: endDate
 *         in: query #参数存放位置。query是存放到请求头里边
 *         required: true
 *         description: 结束日期,例如2017-07-21
 *         type: string
 *     responses:
 *       200:
 *         description: 成功
 */
router.get("/getBloodglucoseByDates", async function (ctx, next) {
  const { userId,startDate,endDate } = ctx.request.query;
  const Op = Sequelize.Op;
  const DATE_START = moment(startDate).format('YYYY-MM-DD 00:00:00');
  const DATE_END = moment(endDate).format('YYYY-MM-DD 23:59:00');
  let bloodglucoses = await Bloodglucose.findAll({
    where: { 
      userId,
      recordTime: { 
        [Op.between]: [
          DATE_START,
          DATE_END,
      ]
      },
     },
    include: {
      model: User,
      attributes: ['username','userId','weight','bmi'] 
    }
  });
  // console.log(bloodglucoses);//findAll返回的数组对象，不需要使用get({ plain: true }
  if (bloodglucoses.length>=0) {
    ctx.body = formatResponse("200", bloodglucoses.length>0?bloodglucoses:[], "success");
  } else {
    ctx.body = formatResponse("500", "", "fail");
  }
});
/**
 * @swagger
 * /bloodglucose/deleteBloodglucose:
 *   get:
 *     security:
 *       - bearerAuth: []
 *     summary: 根据血糖ID删除血糖记录
 *     description: 根据血糖ID删除血糖记录
 *     tags: [血糖记录]
 *     parameters:
 *       - name: bloodglucoseIds
 *         in: query #参数存放位置。query是存放到请求头里边
 *         required: true
 *         description: 血糖ID
 *         schema:
 *          type: array
 *          items:
 *            type: string
 *     responses:
 *       200:
 *         description: 成功
 */
router.get("/deleteBloodglucose", async function (ctx, next) {
  const { bloodglucoseIds } = ctx.request.query;
  const count = await Bloodglucose.destroy({
    where: {
      bloodglucoseId: bloodglucoseIds
    }
  });
  if (count > 0) {
    ctx.body = formatResponse("200", {code:200,message:'血糖删除成功'}, "success");
  } else {
    ctx.body = formatResponse("500", "", "fail");
  }
});
/**
 * @swagger
 * /bloodglucose/getBloodglucoseByPageAndCondition:
 *   get:
 *     security:
 *       - bearerAuth: []
 *     summary: 条件分页查询血糖记录
 *     description: 条件分页查询血糖记录
 *     tags: [血糖记录]
 *     parameters:
 *       - name: userId
 *         in: query #参数存放位置。query是存放到请求头里边
 *         description: 用户ID
 *         type: string
 *       - name: username
 *         in: query #参数存放位置。query是存放到请求头里边
 *         description: 用户名称
 *         type: string
 *       - name: dietStatus
 *         in: query #参数存放位置。query是存放到请求头里边
 *         description: 血糖监测状态（0早餐前 1 早餐后 2午餐前 3午餐后 4晚餐前 5晚餐后 6睡前 7凌晨 8随机）
 *         type: integer
 *       - name: currentPage
 *         in: query #参数存放位置。query是存放到请求头里边
 *         required: true
 *         description: 当前第几页
 *         type: string
 *       - name: pageSize
 *         in: query #参数存放位置。query是存放到请求头里边
 *         required: true
 *         description: 一页几条记录
 *         type: string
 *     responses:
 *       200:
 *         description: 成功
 */
router.get("/getBloodglucoseByPageAndCondition", async function (ctx, next) {
  const { currentPage, pageSize, userId,username, dietStatus} = ctx.request.query;
  offset = (currentPage - 1) * pageSize || 0;
  //条件2：血糖监测状态（0 早餐前 1 早餐后 2午餐前 3午餐后 4晚餐前 5晚餐后 6睡前 7凌晨 8随机）
  const condition1 =dietStatus?{ dietStatus } : null;
  const condition2 =username? { username } : null ;
  const condition3 =userId? { userId } : null ;
  let result = await Bloodglucose.findAndCountAll({
    where: Object.assign({}, condition1), 
    order: [['createdAt', 'DESC']],
    offset,
    limit: parseInt(pageSize),
    include:{
      model: User,
      where:Object.assign({}, condition2,condition3), 
      attributes: ['username','realname','weight','bmi','specialCondition'],
    }
  });
  if (result) {
    ctx.body = formatResponse("200", result, "success");
  } else {
    ctx.body = formatResponse("500", "", "fail");
  }
});

/**
 * @swagger
 * /bloodglucose/updateBloodglucose: #接口访问路径(拼接上之前swagger.js中的host)
 *   post: #请求方式
 *     security:
 *       - bearerAuth: []
 *     summary: 根据血糖ID更新血糖信息  #接口信息
 *     description: 根据血糖ID更新血糖信息 #接口描述
 *     tags: [血糖记录] #接口分组
 *     produces:
 *       - application/json
 *     consumes:
 *       - application/json
 *     requestBody:
 *         content:
 *            application/x-www-form-urlencoded:
 *               schema:
 *                  type: object
 *                  properties:
 *                     bloodglucoseId:          # <!--- form field name
 *                        type: string
 *                        description: 血糖ID
 *                     bloodglucoseValue:          
 *                        type: number
 *                        description: 血糖值
 *                     recordTime:       
 *                        type: string
 *                        description: 记录时间
 *                     dietStatus:          
 *                        type: integer
 *                        enum: [ "0", "1","2","3","4","5","6","7","8"]
 *                        description: 血糖检查状态：0早餐前 1 早餐后 2午餐前 3午餐后 4晚餐前 5晚餐后 6睡前 7凌晨 8随机
 *     responses: #返回结果
 *       200:
 *         description: 成功
 */
router.post("/updateBloodglucose", async function (ctx, next) {
    try {
      let bloodInfo = ctx.request.body;
      bloodInfo = filterColumn(bloodInfo)
      // console.log(1111111111111,bloodInfo)
      let result = await Bloodglucose.update(
        {
          ...bloodInfo
        },
        {
          where: {
            bloodglucoseId: bloodInfo.bloodglucoseId,
          },
        }
      );
      if (result[0] > 0) {
        ctx.body = formatResponse("200", { code: 200, message: '血糖更新成功' }, "success");
      } else {
        ctx.body = formatResponse("500", { code: 500, message: '血糖更新失败' }, "fail");
      }
    } catch (error) {
      ctx.body = formatResponse("500", error, "fail");
    }

});

module.exports = router